import os
import cv2
import numpy as np
from AutoOperation.settings import STATICFILES_DIRS
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw


def makeImageCover(image_bytes, title, image_size, savePath):
    """
    把图片转封面
    @param image_bytes: 图片bytes
    @param title: 素材标题
    @param image_size: 图片尺寸
    @param savePath: 保存地址
    @return: image_byte
    """
    font_size = int(image_size[1] * 0.18)
    font1_size = int(image_size[1] * 0.152)
    fontPath = os.path.join(STATICFILES_DIRS[0], "fonts", "msyhbd.ttc")
    font = ImageFont.truetype(fontPath, font_size)
    font1 = ImageFont.truetype(fontPath, font1_size)
    npArr = np.fromstring(image_bytes, np.uint8)
    image = cv2.imdecode(npArr, cv2.IMREAD_COLOR)
    image = cv2.resize(image, image_size)
    image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    s1 = title[:image_size[0] // font_size // 3]
    s2 = title[image_size[0] // font_size // 3:image_size[0] // font_size // 3 + image_size[0] // font1_size - 1]
    draw = ImageDraw.Draw(image)
    draw.text((15, image_size[1] * 0.611), s1, (255, 255, 0), font=font)
    draw.text((15, image_size[1] * 0.798), s2, (255, 255, 255), font=font1)
    image.save(savePath)
